package com.fiveGroup.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fiveGroup.pojo.OrderInfo;
import com.fiveGroup.pojo.Product;
import com.fiveGroup.pojo.vo.*;
import com.fiveGroup.service.OrderInfoService;
import com.fiveGroup.service.ProductService;
import com.fiveGroup.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/order") // 接口前缀统一为 /api/order
public class OrderController {

    private final OrderInfoService orderInfoService;
    private final ProductService productService;

    public OrderController(OrderInfoService orderInfoService, ProductService productService) {
        this.orderInfoService = orderInfoService;
        this.productService = productService;
    }

    /**
     * 查询买家订单列表
     */
    @GetMapping("/buyerList")
    public DataVo getBuyerOrders(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "5") int size,
                                 @RequestParam(required = false) String keyword) {
        Long userId = UserContextHolder.getUserId();
        // 1. 构建分页对象
        Page<BuyerOrderVo> orderPage = new Page<>(page, size);
        log.error(keyword + "数据");
        QueryWrapper<BuyerOrderVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oi.user_id", userId);
        queryWrapper.eq("oi.is_delete", 0);

        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like("oi.order_sn", keyword)  // 订单编号模糊匹配
                    .or()
                    .like("p.name", keyword)  // 商品名称模糊匹配
            );
        }
        List<BuyerOrderVo> orders = orderInfoService.getBuyerOrders(orderPage, queryWrapper);
        System.out.println(orders);
        orderPage.setRecords(orders);
        return DataVo.success(orderPage);

    }

    /**
     * 查询卖家订单列表
     */
    @GetMapping("/sellerList")
    public DataVo getSellerOrders(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "5") int size,
                                  @RequestParam(required = false) String keyword) {
        Long sellerId = UserContextHolder.getUserId();
        Page<SellerOrderVo> orderPage = new Page<>(page, size);
        QueryWrapper<BuyerOrderVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p.seller_id", sellerId);
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like("oi.order_sn", keyword)  // 订单编号模糊匹配
                    .or()
                    .like("p.name", keyword)  // 商品名称模糊匹配
            );
        }
        List<SellerOrderVo> orders = orderInfoService.getSellerOrders(orderPage, queryWrapper);
        orderPage.setRecords(orders);
        return DataVo.success(orderPage);
    }

    /**
     * 支付订单
     */
    @PostMapping("/pay")
    public DataVo<Boolean> payOrder(@RequestBody PayVo payVo) {

        boolean isSuccess = orderInfoService.payOrder(payVo);

        return isSuccess ? DataVo.success(true) : DataVo.fail(500, "支付失败");
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    public DataVo<Boolean> cancelOrder(@RequestBody OrderInfo orderInfo) {

        boolean isSuccess = orderInfoService.cancelOrder(orderInfo);

        return isSuccess ? DataVo.success() : DataVo.fail(500, "取消失败");
    }

    //获取订单详情
    @GetMapping("/detail/{orderId}")
    public DataVo<OrderDetailVo> getOrderDetail(@PathVariable Long orderId) {
        OrderDetailVo orderDetailVo = orderInfoService.getOrderDetail(orderId);
        return DataVo.success(orderDetailVo);
    }

    //修改订单地址
    @PutMapping("/updateAddress")
    public DataVo updateAddress(@RequestBody OrderInfo orderInfo) {
        log.error(orderInfo.toString());
        boolean isSuccess = orderInfoService.updateById(orderInfo);
        log.error(String.valueOf(isSuccess));
        return isSuccess ? DataVo.success() : DataVo.fail("修改订单地址失败");
    }

    //创建订单
    @PostMapping("/create")
    public DataVo createOrder(@RequestBody OrderInfo orderInfo) {
        if (productService.getById(orderInfo.getProductId()) == null) return DataVo.fail("失败");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePart = dateFormat.format(new Date());
        // 查询当前日期已有订单数量，避免订单号重复
        int existingOrderCount = orderInfoService.getOrderCountByDate(new Date());
        int sequence = existingOrderCount + 1;
        String sequencePart = String.format("%03d", sequence);

        orderInfo.setOrderSn(String.format("ORD" + datePart + sequencePart));
        orderInfo.setUserId(UserContextHolder.getUserId());
        orderInfo.setStatus(1);
        orderInfo.setCreatedAt(new Date());
        boolean isSuccess = orderInfoService.save(orderInfo);
        if (isSuccess) {
            // 3. 更新商品状态为已下架(3)
            Product product = new Product();
            product.setId(orderInfo.getProductId());
            product.setStatus(3); // 设置为已下架
            productService.updateById(product);
            return DataVo.success(orderInfo);
        }

        return DataVo.fail("创建订单失败");
    }


    // 购物车批量创建订单
    @PostMapping("/createBatch")
    public DataVo createBatchOrders(@RequestBody List<OrderInfo> orderInfoList) {
        if (orderInfoList == null || orderInfoList.isEmpty()) {
            return DataVo.fail("订单列表不能为空");
        }
        // 1. 获取所有商品id
        List<Long> productIds = orderInfoList.stream()
                .map(OrderInfo::getProductId)
                .collect(Collectors.toList());

        // 通过id查询所有商品
        List<Product> products = productService.listByIds(productIds);

        Map<Long, Integer> productMap = products.stream()
                .collect(Collectors.toMap(Product::getId, Product::getStatus));

        // 检查每个商品状态
        for (OrderInfo orderInfo : orderInfoList) {
            Integer status = productMap.get(orderInfo.getProductId());
            if (status == null) {
                return DataVo.fail("商品不存在，商品ID：" + orderInfo.getProductId());
            }
            if (status != 1) {
                return DataVo.fail("商品不可购买，商品ID：" + orderInfo.getProductId() + "，当前状态：" + status);
            }
        }

        // 2. 生成订单号并设置订单信息
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePart = dateFormat.format(new Date());

        // 查询当前日期已有订单数量，避免订单号重复
        int existingOrderCount = orderInfoService.getOrderCountByDate(new Date());
        log.error(existingOrderCount + "");
        int sequence = existingOrderCount + 1;

        List<OrderInfo> savedOrders = new ArrayList<>();

        for (OrderInfo orderInfo : orderInfoList) {
            // 生成唯一订单号
            String sequencePart = String.format("%03d", sequence++);
            String orderSn = "ORD" + datePart + sequencePart;

            // 设置订单信息
            orderInfo.setOrderSn(orderSn);
            orderInfo.setUserId(UserContextHolder.getUserId());
            orderInfo.setStatus(1); // 设置订单状态，1表示待支付
            orderInfo.setCreatedAt(new Date());

            // 保存订单
            boolean isSuccess = orderInfoService.save(orderInfo);
            if (isSuccess) {
                savedOrders.add(orderInfo);

                // 3. 更新商品状态为已下架(3)
                Product product = new Product();
                product.setId(orderInfo.getProductId());
                product.setStatus(3); // 设置为已下架
                productService.updateById(product);
            }
        }

        if (savedOrders.size() == orderInfoList.size()) {
            return DataVo.success("成功创建" + savedOrders.size() + "个订单");
        } else {
            return DataVo.fail("部分订单创建失败，成功创建" + savedOrders.size() + "个订单");
        }
    }
}